/*
 * @Author: 马思宁 598138645@qq.com
 * @Date: 2024-04-08 09:53:08
 * @LastEditors: 马思宁 598138645@qq.com
 * @LastEditTime: 2024-05-07 16:53:09
 * @FilePath: \v-manage\src\store\modules\user.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { defineStore } from 'pinia';
import { login, logout } from '@/api/login';
import { getToken, setToken, removeToken } from '@/utils/auth';

const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    id: '',
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
  }),
  actions: {
    // 登录
    login(userInfo: { username: string; password: string; code: string; uuid: string }) {
      return new Promise<void>((resolve, reject) => {
        login(userInfo)
          .then((res: any) => {
            if (res.code === 200) {
              setToken(res.token);
              this.token = res.token;
              resolve();
            }
          })
          .catch((error: any) => {
            reject(error);
          });
      });
    },
    // 获取用户信息
    getInfo() {},
    // 退出系统
    logOut() {
      return new Promise<void>((resolve, reject) => {
        logout()
          .then(() => {
            this.token = '';
            this.roles = [];
            this.permissions = [];
            removeToken();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
  },
});

export default useUserStore;
